﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace T_settlement.Infrastructure
{
    public class BaseRepository<T> : IRepository<T> where T : class
    {
        private readonly MyDbContext _dbContext;

        public BaseRepository(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }


        public async Task<int> AddAsync(T t)
        {
            await _dbContext.AddAsync(t);
            var res = await _dbContext.SaveChangesAsync();
            return res;
        }

        public async Task<int> Delete(int id)
        {
            var info = _dbContext.Set<T>().Find(id);
            _dbContext.Remove(info);
            return await _dbContext.SaveChangesAsync();

        }



        public async Task<List<T>> GetAllAsync()
        {
            return await _dbContext.Set<T>().ToListAsync();
        }


        public async Task<T> GetAllAsync(Expression<Func<T, bool>> expre)
        {
            DbSet<T> dbSet = _dbContext.Set<T>();
            return await dbSet.FirstOrDefaultAsync(expre);
        }


        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            return await _dbContext.Set<T>().Where(expre).ToListAsync();
        }

        public async Task<T> GetModelAsync(int id)
        {
            return await _dbContext.Set<T>().FindAsync(id);
        }

        public async Task<int> UpdateAsync(T t)
        {
            _dbContext.Update(t);
            return await _dbContext.SaveChangesAsync();
        }

        public async Task<int> UpdateAsyncRange(List<T> info)
        {

            _dbContext.UpdateRange(info);
            return await _dbContext.SaveChangesAsync();
        }
    }
}
